package com.aispeech.imgany.net;

import android.text.TextUtils;
import android.util.Log;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

/**
 * @author rain  03.01 2018
 */

public class PostImg {

    private final String TAG = "PostImg";
    private IPostImgListener mListener;
    private OkHttpClient mOkHttpClient;

    public PostImg(IPostImgListener listener) {
        mListener = listener;
        mOkHttpClient = new OkHttpClient();
    }

//    /**
//     * @param uploadUrl 上传路径参数
//     * @param uploadFilePath 文件路径
//     * @category 上传文件至Server的方法
//     * @author ylbf_dev
//     */
//    public void uploadFile(final String uploadUrl, final String uploadFilePath, final String wantType) {
//        Log.d(TAG, "uploadFile with: uploadUrl = " + uploadUrl + ", uploadFilePath = " + uploadFilePath + ", wantType = " + wantType + "");
//
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//
//                String end = "\r\n";
//                String hyphens = "------";
//                String boundary = "******";
//
//                try {
//                    URL url = new URL(uploadUrl);
//                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//
//                    httpURLConnection.setConnectTimeout(8 * 1000);//超时8秒
//
////                    String cookieToken = getCookie(uploadUrl, httpURLConnection);
////                    Log.d(TAG, "uploadFile: token = " + cookieToken);
////
////                    if (TextUtils.isEmpty(cookieToken)) {
////                        VoiceEngineManage.getInstance().playTTS("网络问题,无法识别!请稍后再试!");
////                    } else {
//                    httpURLConnection.setDoInput(true);
//                    httpURLConnection.setDoOutput(true);
//                    httpURLConnection.setUseCaches(false);
//                    httpURLConnection.setRequestProperty("Charset", "UTF-8");
//                    httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
//                    httpURLConnection.setRequestMethod("POST");
////                    httpURLConnection.setRequestProperty("Cookie", "csrftoken=" + cookieToken);
//                    httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=----" + boundary);
//
//                    DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
//                    dos.writeBytes(hyphens + boundary + end);
////                    dos.writeBytes("Content-Disposition: form-data; name=\"csrfmiddlewaretoken\"" + end);
////                    dos.writeBytes(hyphens + boundary + end);
//                    String[] tmpName = uploadFilePath.split(File.separator);
//                    String imgName = tmpName[tmpName.length - 1];
//
//                    Log.d(TAG, "run: img name = " + imgName);
//
//                    dos.writeBytes("Content-Disposition: form-data; name=\"img\"; filename=\"" + imgName + "\"" + end);
//                    dos.writeBytes("Content-Type: image/png" + end);
//                    dos.writeBytes(end);
//                    dos.writeBytes(end);
//
//                    // 文件通过输入流读到Java代码中-+++++++++++++++++++++++++++++
//                    FileInputStream fis = new FileInputStream(uploadFilePath);
//                    byte[] buffer = new byte[8192]; // 8k
//                    int count = 0;
//                    while ((count = fis.read(buffer)) != -1) {
//                        dos.write(buffer, 0, count);
//                    }
//                    fis.close();
//                    System.out.println("file send to server............");
//
//                    dos.writeBytes(hyphens + boundary + end);
//                    dos.writeBytes("Content-Disposition: form-data; name=\"want\"" + end);
//                    dos.writeBytes(end);
//                    dos.writeBytes(wantType);
//
//                    dos.writeBytes(end);
//                    dos.writeBytes(hyphens + boundary + "--" + end);
//                    dos.flush();
//
//                    int responseCode = httpURLConnection.getResponseCode();
//                    Log.d(TAG, "run: responseCode= " + responseCode);
//
//                    if (responseCode == 200) {
//                        // 读取服务器返回结果
//                        InputStream is = httpURLConnection.getInputStream();
//                        InputStreamReader isr = new InputStreamReader(is, "utf-8");
//                        BufferedReader br = new BufferedReader(isr);
//
//                        String valueString;
//                        StringBuilder sb = new StringBuilder();
//
//                        while ((valueString = br.readLine()) != null) {
//                            Log.d(TAG, "getCookie: value = " + valueString);
//                            sb.append(valueString);
//                        }
//                        String imgResult = sb.toString();
//                        Log.d(TAG, "run: img result = " + imgResult);
//                        if (TextUtils.isEmpty(imgResult)) {
//                            mListener.onError("抱歉,我在网上找了一圈也没查到结果!");
//                        } else {
//                            Document document = Jsoup.parseBodyFragment(sb.toString());
//                            Elements guessWordElement = document.select("p[id=guessWord]");
//                            Elements baikeElement = document.select("p[id=baike]");
//                            String guessWord = guessWordElement.text();
//                            String baike = baikeElement.text();
//
//                            Log.d(TAG, "run: guess = " + guessWord);
//                            Log.d(TAG, "run: baike = " + baike);
//
//                            if (!TextUtils.isEmpty(guessWord)) {
//                                mListener.onResult("有可能是" + guessWord + "吧!");
//                            } else {
//                                mListener.onError("抱歉,我在网上找了一圈也没查到结果!");
//                            }
////
//                            mListener.onDetailsResult(TextUtils.isEmpty(baike) ? "没有查到详细信息" : baike);
//                        }
//
//                        dos.close();
//                        is.close();
//
//                    } else {
//                        mListener.onError("暂时找不到哦!请稍后再试!");
//                    }
////                    }
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    mListener.onError("网络不佳,无法识别!请稍后再试!");
//                }
//            }
//
//
//        }).start();
//
//    }
//
//    private String getCookie(String tryUrl, HttpURLConnection httpURLConnection) {
//        Log.d(TAG, "getCookie with: url = " + tryUrl + "");
//        try {
//            httpURLConnection.setRequestMethod("GET");
//            int code = httpURLConnection.getResponseCode();
//            Log.d(TAG, "getCookie: code = " + code);
//            if (code == 200) {
//                InputStream inputStream = httpURLConnection.getInputStream();
//                InputStreamReader isr = new InputStreamReader(inputStream, "utf-8");
//                BufferedReader br = new BufferedReader(isr);
//                String valueString;
//                StringBuilder sb = new StringBuilder();
//
//                while ((valueString = br.readLine()) != null) {
//                    Log.d(TAG, "getCookie: value = " + valueString);
//                    sb.append(valueString);
//                }
//                Document document = Jsoup.parseBodyFragment(sb.toString());
//                Elements select = document.select("input[name=csrfmiddlewaretoken]");
//                String value = select.attr("value");
//                return value;
//            }
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return "";
//    }

    /**
     * 上传文件
     *
     * @param paramsMap 参数
     */
    public void uploadFile(HashMap<String, Object> paramsMap) {
        try {
            //补全请求地址
//            String requestUrl = String.format("%s/%s", upload_head, actionUrl);
//            String requestUrl = actionUrl;

            MultipartBody.Builder builder = new MultipartBody.Builder();
            //设置类型
            builder.setType(MultipartBody.FORM);
            //追加参数
            for (String key : paramsMap.keySet()) {
                Object object = paramsMap.get(key);
                if (!(object instanceof File)) {
                    builder.addFormDataPart(key, object.toString());
                } else {
                    File file = (File) object;
                    builder.addFormDataPart(key, file.getName(), RequestBody.create(null, file));
                }
            }
            //创建RequestBody
            RequestBody body = builder.build();
            //创建Request
            final Request request = new Request.Builder().url(UrlConfig.POST_URL).post(body).build();
            //单独设置参数 比如读取超时时间
            final Call call = mOkHttpClient.newBuilder().writeTimeout(15000, TimeUnit.SECONDS).build().newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e(TAG, e.toString());
                    mListener.onError("抱歉, 网络好像不行了, 再稍后试试吧");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.e(TAG, "response ----->" + string);

                        if (TextUtils.isEmpty(string)) {
                            mListener.onError("抱歉,我在网上找了一圈也没查到结果!");
                        } else {
                            Document document = Jsoup.parseBodyFragment(string);
                            Elements resultWordElement = document.select("p[id=result]");
                            String result = resultWordElement.text();
                            Log.d(TAG, "onResponse: result = " + result);

                            mListener.onDetailsResult(result);

//                            Elements baikeElement = document.select("p[id=baike]");
//                            String guessWord = guessWordElement.text();
//                            String baike = baikeElement.text();
//
//                            Log.d(TAG, "run: guess = " + guessWord);
//                            Log.d(TAG, "run: baike = " + baike);
//
//                            if (!TextUtils.isEmpty(guessWord)) {
//                                mListener.onResult("有可能是" + guessWord + "吧!");
//                            } else {
//                                mListener.onError("抱歉,我在网上找了一圈也没查到结果!");
//                            }
//                            if (!TextUtils.isEmpty(baike)){
//                                mListener.onDetailsResult(baike);
//                            }
                        }
                    } else {
                        mListener.onError("抱歉,网络好像出问题了,暂时无法检索哦!");
                    }
                }
            });
        } catch (Exception e) {
            Log.e(TAG, e.toString());
            mListener.onError("抱歉,哪里好像出问题了,暂时无法检索哦! ");
        }
    }
}
